package com.xu.wemall.commons.components;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xu.wemall.commons.utils.NotResultWrap;
import com.xu.wemall.commons.utils.ResultObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice(basePackages = "com.xu.wemall.controller")
public class ResultControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        log.info("判断是否需要进行返回值包装");
        /*如果返回Result不需要进行包装，
        如果接口使用了@NotResultWrap注解表示不需要进行包装，只对成功的请求进行包装
        异常情况统一放到全局异常中进行处理*/
        return !(returnType.getParameterType().equals(ResultObject.class) || returnType.hasMethodAnnotation(
                NotResultWrap.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        log.info("进行返回值包装");
        ResultObject<Object> resultObject = new ResultObject<>();
        //String类型不能直接包装，需要进行特殊处理
        if (returnType.getParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 使用jackson将返回数据转换为json
                return objectMapper.writeValueAsString(resultObject.success(body));
            } catch (JsonProcessingException e) {
                //这里会走统一异常处理
                throw new RuntimeException("String类型返回值包装异常");
            }
        }
        return resultObject.success(body);
    }
}